package org.apache.james.mime4j.decoder;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class LineBreakingOutputStream extends FilterOutputStream
{
  private static final byte[] CRLF;
  private int lineLength;
  private int linepos = 0;

  static
  {
    byte[] arrayOfByte = new byte[2];
    arrayOfByte[0] = 13;
    arrayOfByte[1] = 10;
    CRLF = arrayOfByte;
  }

  public LineBreakingOutputStream(OutputStream paramOutputStream, int paramInt)
  {
    super(paramOutputStream);
    this.lineLength = 76;
    this.lineLength = paramInt;
  }

  public final void write(int paramInt)
    throws IOException
  {
    if (this.linepos >= this.lineLength)
    {
      this.out.write(CRLF);
      this.linepos = 0;
    }
    this.out.write(paramInt);
    this.linepos = (1 + this.linepos);
  }

  public final void write(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
    throws IOException
  {
    while (true)
    {
      while (true)
      {
        if (paramInt2 <= 0)
          return;
        if (paramInt2 + this.linepos <= this.lineLength)
          break;
        int i = this.lineLength - this.linepos;
        if (i > 0)
        {
          this.out.write(paramArrayOfByte, paramInt1, i);
          paramInt1 += i;
          paramInt2 -= i;
        }
        this.out.write(CRLF);
        this.linepos = 0;
      }
      this.out.write(paramArrayOfByte, paramInt1, paramInt2);
      this.linepos = (paramInt2 + this.linepos);
      paramInt2 = 0;
    }
  }
}